import React, { useState } from 'react';
import { Card, Image, Tag, Button, Space, Tooltip, Badge } from 'antd';
import { 
  HeartOutlined, 
  HeartFilled, 
  EyeOutlined, 
  ShoppingCartOutlined,
  EnvironmentOutlined,
  UserOutlined,
  ClockCircleOutlined
} from '@ant-design/icons';
import type { Product, ProductStatus } from '../../../types/product';
import { 
  PRODUCT_CATEGORY_DISPLAY_NAMES, 
  PRODUCT_CONDITION_DISPLAY_NAMES,
  PRODUCT_STATUS_DISPLAY_NAMES,
  TRANSACTION_METHOD_DISPLAY_NAMES,
  getProductCoverImage,
  isProductPurchasable
} from '../../../types/product';

interface ProductCardProps {
  /** 商品数据 */
  product: Product;
  /** 是否显示收藏按钮 */
  showFavorite?: boolean;
  /** 是否显示购物车按钮 */
  showCart?: boolean;
  /** 是否显示详细视图 */
  detailed?: boolean;
  /** 点击商品回调 */
  onClick?: (product: Product) => void;
  /** 收藏回调 */
  onFavorite?: (productId: string, favorited: boolean) => void;
  /** 加入购物车回调 */
  onAddToCart?: (product: Product) => void;
  /** 自定义渲染操作区域 */
  renderActions?: (product: Product) => React.ReactNode;
  /** 卡片尺寸 */
  size?: 'small' | 'default' | 'large';
  /** 是否正在加载 */
  loading?: boolean;
}

/**
 * 商品卡片组件
 * 支持不同状态展示、收藏功能、响应式布局
 */
const ProductCard: React.FC<ProductCardProps> = ({
  product,
  showFavorite = true,
  showCart = true,
  detailed = false,
  onClick,
  onFavorite,
  onAddToCart,
  renderActions,
  size = 'default',
  loading = false
}) => {
  const [isFavorited, setIsFavorited] = useState(product.favoriteCount > 0);
  const [favoriteCount, setFavoriteCount] = useState(product.favoriteCount);

  // 处理收藏点击
  const handleFavoriteClick = (e: React.MouseEvent) => {
    e.stopPropagation();
    const newFavorited = !isFavorited;
    setIsFavorited(newFavorited);
    setFavoriteCount(newFavorited ? favoriteCount + 1 : Math.max(0, favoriteCount - 1));
    onFavorite?.(product.id, newFavorited);
  };

  // 处理加入购物车
  const handleAddToCart = (e: React.MouseEvent) => {
    e.stopPropagation();
    onAddToCart?.(product);
  };

  // 处理卡片点击
  const handleCardClick = () => {
    onClick?.(product);
  };

  // 获取商品状态标签颜色
  const getStatusColor = (status: ProductStatus): string => {
    switch (status) {
      case 'active': return 'green';
      case 'sold': return 'red';
      case 'pending': return 'orange';
      case 'rejected': return 'gray';
      case 'inactive': return 'default';
      default: return 'default';
    }
  };

  // 获取商品新旧程度颜色
  const getConditionColor = (condition: string): string => {
    switch (condition) {
      case 'new': return 'green';
      case 'like_new': return 'blue';
      case 'very_good': return 'cyan';
      case 'good': return 'orange';
      default: return 'default';
    }
  };

  // 计算显示价格
  const displayPrice = product.originalPrice && product.originalPrice > product.price 
    ? `¥${product.price} (原价¥${product.originalPrice})` 
    : `¥${product.price}`;

  // 卡片尺寸样式
  const cardSizeStyles = {
    small: {
      card: 'w-64',
      image: 'h-32',
      title: 'text-sm',
      price: 'text-base'
    },
    default: {
      card: 'w-80',
      image: 'h-48',
      title: 'text-base',
      price: 'text-lg'
    },
    medium: {
      card: 'w-80',
      image: 'h-48',
      title: 'text-base',
      price: 'text-lg'
    },
    large: {
      card: 'w-96',
      image: 'h-64',
      title: 'text-lg',
      price: 'text-xl'
    }
  };

  const sizeStyle = cardSizeStyles[size];

  // 基础卡片内容
  const baseCardContent = (
    <Card
      loading={loading}
      hoverable
      className={`product-card ${sizeStyle.card} transition-all duration-300 hover:shadow-lg border-gray-200`}
      cover={
        <div className="relative">
          <Image
            alt={product.title}
            src={getProductCoverImage(product) || '/placeholder-image.jpg'}
            preview={false}
            className={`object-cover ${sizeStyle.image} w-full`}
            placeholder={
              <div className="flex items-center justify-center bg-gray-100 h-full">
                <div className="text-gray-400">图片加载中...</div>
              </div>
            }
          />
          
          {/* 状态标签 */}
          <div className="absolute top-2 left-2">
            <Badge 
              count={PRODUCT_STATUS_DISPLAY_NAMES[product.status] as React.ReactNode} 
              color={getStatusColor(product.status)}
              className="text-xs"
            />
          </div>

          {/* 收藏按钮 */}
          {showFavorite && (
            <div className="absolute top-2 right-2">
              <Button
                type="text"
                shape="circle"
                className={`favorite-btn ${isFavorited ? 'text-red-500' : 'text-white'} bg-black bg-opacity-30 hover:bg-opacity-50`}
                icon={isFavorited ? React.createElement(HeartFilled) : React.createElement(HeartOutlined)}
                onClick={handleFavoriteClick}
              />
            </div>
          )}

          {/* 浏览量 */}
          <div className="absolute bottom-2 left-2">
            <Tag color="black" className="bg-black bg-opacity-50 text-white text-xs">
              <EyeOutlined className="mr-1" />
              {product.viewCount}
            </Tag>
          </div>

          {/* 收藏数 */}
          <div className="absolute bottom-2 right-2">
            <Tag color="black" className="bg-black bg-opacity-50 text-white text-xs">
              <HeartOutlined className="mr-1" />
              {favoriteCount}
            </Tag>
          </div>
        </div>
      }
      onClick={handleCardClick}
    >
      <Card.Meta
        title={
          <div className={`font-semibold ${sizeStyle.title} truncate`} title={product.title}>
            {product.title}
          </div>
        }
        description={
          <div className="space-y-2">
            {/* 价格信息 */}
            <div className={`font-bold text-red-500 ${sizeStyle.price}`}>
              {displayPrice}
            </div>

            {/* 商品信息 */}
            <div className="flex flex-wrap gap-1">
              <Tag color={getConditionColor(product.condition)}>
                {PRODUCT_CONDITION_DISPLAY_NAMES[product.condition]}
              </Tag>
              <Tag color="blue">
                {PRODUCT_CATEGORY_DISPLAY_NAMES[product.category]}
              </Tag>
              {product.isNegotiable && (
                <Tag color="orange">可议价</Tag>
              )}
              {product.isFreeShipping && (
                <Tag color="green">包邮</Tag>
              )}
            </div>

            {/* 交易方式 */}
            <div className="text-xs text-gray-500">
              <ShoppingCartOutlined className="mr-1" />
              {TRANSACTION_METHOD_DISPLAY_NAMES[product.transactionMethod]}
            </div>

            {/* 详细视图的额外信息 */}
            {detailed && (
              <>
                <div className="text-sm text-gray-600 line-clamp-2">
                  {product.description}
                </div>
                
                <div className="flex items-center justify-between text-xs text-gray-500">
                  <Space size="small">
                    <UserOutlined />
                    <span>{product.publisher.username}</span>
                    {product.publisher.isStudentVerified && (
                      <Tag color="green">已认证</Tag>
                    )}
                  </Space>
                  
                  <Space size="small">
                    <EnvironmentOutlined />
                    <span>{product.location.school}</span>
                  </Space>
                </div>

                <div className="text-xs text-gray-400">
                  <ClockCircleOutlined className="mr-1" />
                  {new Date(product.publishedAt).toLocaleDateString()}
                </div>
              </>
            )}
          </div>
        }
      />

      {/* 操作区域 */}
      <div className="mt-4 pt-3 border-t border-gray-100">
        {renderActions ? (
          renderActions(product)
        ) : (
          <div className="flex justify-between items-center">
            <Tooltip title={isProductPurchasable(product) ? "购买商品" : "商品已售罄"}>
              <Button
                type="primary"
                size="small"
                disabled={!isProductPurchasable(product)}
                icon={React.createElement(ShoppingCartOutlined)}
                onClick={handleAddToCart}
              >
                {isProductPurchasable(product) ? '立即购买' : '已售罄'}
              </Button>
            </Tooltip>
            
            <Space>
              {showCart && (
                <Tooltip title="加入购物车">
                <Button
                  size="small"
                  disabled={!isProductPurchasable(product)}
                  icon={React.createElement(ShoppingCartOutlined)}
                  onClick={handleAddToCart}
                >
                购物车
                </Button>
                </Tooltip>
              )}
              
              <Tooltip title="查看详情">
                <Button size="small" type="link" onClick={handleCardClick}>
                  详情
                </Button>
              </Tooltip>
            </Space>
          </div>
        )}
      </div>
    </Card>
  );

  return baseCardContent;
};

export default ProductCard;